package com.base;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.dao.ParkManagerDao;

public class BaseDao{

	private static final Logger log = Logger.getLogger(ParkManagerDao.class);
	
	protected Session session=null;
	protected SessionFactory sessionFactory; 

	public BaseDao(){}
	
	public void closeSession()
	{
		if(session!=null && session.isOpen())
			session.close();
		log.info(BaseDao.class + " session.close()");
	}
	@Override
	protected void finalize() throws Throwable {
		this.closeSession();
		super.finalize();
	}



//	public SessionFactory configureSessionFactory()throws HibernateException {
//		Configuration configuration = new Configuration();
//		configuration.configure();
//		serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
//		sessionFactory = configuration.buildSessionFactory(serviceRegistry);
//		log.info("configureSessionFactory");
//		return sessionFactory;
//	}

	public Session getSession(){

		return HibernateUtil.getSession();
	 
//    	if(sessionFactory==null){
//    		sessionFactory = this.configureSessionFactory();
//    	}
//    	try{
//			session=sessionFactory.getCurrentSession();
//		}catch (Exception e) {
//			e.printStackTrace();
//		}
//		return session;
	}

	private static Configuration configuration = null;
	private static ServiceRegistry serviceRegistry = null;

	private ApplicationContext ctx; 

	public SessionFactory newSessionFactory() { 

		String[] configLocations = new String[] {"classpath:applicationContext.xml"}; 
		ctx = new ClassPathXmlApplicationContext(configLocations); 
		return ctx.getBean("sessionFactory", SessionFactory.class);

	} 

	public static void main(String args[]){

		BaseDao bd = new BaseDao();
		SessionFactory sf = bd.newSessionFactory();
		System.out.println("sf="+sf);

	}
	 
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	 
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}


}